<template>
  <div class="article-list">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" :success-text="refreshText" :success-duration="1500">
     <van-list
      v-model="loading"
      :finished="finished"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      finished-text="没有更多了"
      @load="onLoad">
      <!-- <van-cell v-for="item in list" :key="item.art_id" :title="item.title" /> -->
      <articleItem
      v-for="item in list"
      :key="item.art_id.toString()"
      :artObj="item"
      ></articleItem>
    </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import articleItem from '@/components/article-item'
export default {
  name: 'articleIndex',
  components: {
    articleItem
  },
  props: {
    obj: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      list: [], // 存储列表数据的数组
      loading: false, // 控制加载中 loading 状态
      finished: false, // 控制数据加载结束的状态
      error: false,
      isLoading: false, // 下拉加载中的状态
      refreshText: '' // 刷新成功或失败的提示文案
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // 初始化或滚动到底部的时候会触发调用 onLoad
    async onLoad () {
      try {
        const { data } = await getArticles({
          channel_id: this.obj.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        // console.log(data.data.results)
        const { results } = data.data
        // console.log(results)
        this.list.push(...results)
        this.loading = false
        // results = [] //测试finished为true情况
        if (results.length <= 0) {
          this.finished = true
        } else {
          this.timestamp = data.data.pre_timestamp
        }
      } catch (error) {
        console.log('获取信息失败！', error)
        this.$toast('获取信息失败！')
        this.error = true
        this.loading = false
      }
    },
    async onRefresh() {
      try {
        const { data } = await getArticles({
          channel_id: this.obj.id,
          timestamp: Date.now(),
          with_top: 1
        })

        const { results } = data.data
        this.list.unshift(...results)
        // this.$toast('请求数据成功！')
        // 关掉下拉加载中
        this.isLoading = false
        // 刷新成功后的提示文案
        this.refreshText = `更新成功，更新了${results.length}条数据！`
      } catch (error) {
        // this.$toast('请求数据失败',error)
        this.isLoading = false
        this.refreshText = '更新数据失败！ '
      }
    }
  }
}
</script>

<style lang="less" scoped>
.article-list {
  overflow-y: auto;
  height: 79vh;
}
</style>
